const app = new Vue({
    el: '#geo_point',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 船舶数据请求配置表格数据
            dataList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                name: "",
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            imageList: [],
            imagePreviewVisible: false,
            previewImageList: []
        }
    },
    computed: {
        PointTypeNameMap() {
            return window.PointTypeNameMap || {};
        }
    },
    mounted() {
        this.getList();
        this.txMapEventHandle()
    },
    methods: {
        /** 查询船舶数据请求配置列表 */
        getList() {
            this.loading = true;
            $.ajax({
                type: "get",
                url: "/geo/point/page",
                data: this.queryParams,
                contentType: "application/json",
                async: true,
                dataType: "json",
                success(data) {
                    if (data && data.code === 200) {
                        app.dataList = data.data.list
                        app.total = data.data.totalCount
                    } else {
                        app.$message.error(data.msg)
                    }
                    app.loading = false
                }
            });
        },
        /**地图选点事件  */
        txMapEventHandle() {
            window.addEventListener('message', function (event) {
                // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
                let loc = event.data;
                if (loc && loc.module === 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
                    if (loc) {
                        app.form.address = loc.poiaddress + loc.poiname
                        app.form.address = loc.poiaddress + loc.poiname
                        app.form.lon = loc.latlng.lng
                        app.form.lat = loc.latlng.lat
                    }
                }
            }, false);
        },
        // 分页, 每页条数
        pageSizeChangeHandle(val) {
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = val
            this.getList()
        },
        // 分页, 当前页
        pageCurrentChangeHandle(val) {
            this.queryParams.pageNum = val
            this.getList()
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                lon: null,
                lat: null,
                type: null,
                address: null,
                remark: null,
                imageBase64List: []
            };
        },
        getPointTypeName(type) {
            return PointTypeNameMap[type] || "未知";
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                devCode: "",
                tcpIp: "",
                tcpPort: "",
                pageNum: 1,
                pageSize: 10
            }
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加标记信息";
        },
        handleImageChange(file, fileList) {
            const reader = new FileReader();
            reader.onload = () => {
                const base64 = reader.result;
                this.form.imageBase64List.push({img: base64});
                this.imageList = fileList;
            };
            reader.readAsDataURL(file.raw); // 带 data:image/jpeg;base64,...
        },
        handleImageRemove(file, fileList) {
            // 简化处理：基于 name 同步删除
            const index = this.imageList.findIndex(f => f.uid === file.uid);
            if (index !== -1) {
                this.form.imageBase64List.splice(index, 1);
            }
            this.imageList = fileList;
        },
        /**预览图片*/
        previewImages(id) {
            //获取图片信息
            $.ajax({
                type: "get",
                url: "/geo/point/pic/listByPointId",
                data: {pointId: id},
                contentType: "application/json",
                async: true,
                dataType: "json",
                success(val) {
                    if (val && val.code === 200) {
                        app.previewImageList = val.data.map(i => i.img);
                        app.imagePreviewVisible = true;
                    }
                }
            })
        },
        beforeUpload(file) {
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                this.$message.error('只能上传 JPG/PNG 格式的图片!');
            }
            if (!isLt2M) {
                this.$message.error('图片大小不能超过 2MB!');
            }
            return isImage && isLt2M;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            $.ajax({
                type: "get",
                url: "/geo/point/info/" + id,
                data: this.queryParams,
                contentType: "application/json",
                async: true,
                dataType: "json",
                success(data) {
                    if (data && data.code === 200) {
                        app.form = data.data
                        //获取图片信息
                        $.ajax({
                            type: "get",
                            url: "/geo/point/pic/listByPointId",
                            data: {pointId: id},
                            contentType: "application/json",
                            async: true,
                            dataType: "json",
                            success(val) {
                                if (val && val.code === 200) {
                                    app.form.imageBase64List = val.data.map(item=>{
                                        return {img: item.img, id: item.id}
                                    })
                                    app.imageList = val.data.map(item=>{
                                        return {url: item.img, uid: item.id}
                                    })
                                }
                            }

                        })
                        app.open = true;
                        app.title = "修改标记信息";
                    } else {
                        app.$message.error(data.msg)
                    }
                }
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.form.status = 0;
                    $.ajax({
                        type: "post",
                        url: `/geo/point/${this.form.id ? 'updateWithPic' : 'saveWithPic'}`,
                        data: JSON.stringify(this.form),
                        contentType: "application/json",
                        async: true,
                        dataType: "json",
                        success(data) {
                            if (data && data.code === 200) {
                                app.$message.success(`${app.form.id ? '修改成功' : '新增成功'}`)
                                app.open = false;
                                app.getList();
                            } else {
                                app.$message.error(data.msg)
                            }
                        }
                    });
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm(`是否确认删除编号${row.id}的配置项？`)
                .then(function () {
                    $.ajax({
                        type: "post",
                        url: "/geo/point/delete/" + ids,
                        contentType: "application/json",
                        async: true,
                        dataType: "json",
                        success(data) {
                            if (data && data.code === 200) {
                                app.getList();
                                app.$message.success("删除成功");
                            } else {
                                app.$message.error(data.msg)
                            }
                        }
                    });
                })
        },
        /** 导出按钮操作 */
        handleExport() {
            $.ajax({
                type: "post",
                url: "/geo/point/export",
                data: JSON.stringify(this.queryParams),
                contentType: "application/json",
                async: true,
                xhrFields: {
                    responseType: 'blob',
                },
                success(blob) {
                    const reader = new FileReader();
                    reader.readAsDataURL(blob);
                    reader.onload = function (e) {
                        const a = document.createElement('a');
                        a.download = `设备列表.xlsx`;
                        a.href = e.target.result;
                        $("body").append(a);  // 修复firefox中无法触发click
                        a.click();
                        $(a).remove();
                        app.$message({
                            message: "导出成功",
                            type: "success",
                            center: true
                        })
                    }
                }
                , error() {
                    app.$message({
                        message: "导出失败，请重试",
                        type: "error",
                        center: true
                    })
                }
            })
        },
    }
})
